import 'package:dio/dio.dart';

import '../../bean/requesterror_bean.dart';
import '../../common/base_config.dart';

class HttpManager {
  static HttpManager _instance = HttpManager._internal();
  Dio _dio;
  Map<String, dynamic> m = {"code": -1, "msg": "请求失败", "data": "请求失败"};

  factory HttpManager() => _instance;

  ///通用全局单例，第一次使用时初始化
  HttpManager._internal({String baseUrl}) {
    if (null == _dio) {
      _dio =
          Dio(BaseOptions(baseUrl: BaseConfig.BASE_URL, connectTimeout: 15000));
      _dio.interceptors
          .add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
        return options; //continue
      }, onResponse: (Response response) async {
        // 接收返回的信息
        Map res = response.data;

        // 临时量（针对数据未null时，dio库将返回{"code": 1, "data": null, "msg": null}的情况）
        var _temData;

        // 将行为错误与网络错误统一返回到异常中
        if (res["code"] != 1) {
          // 业务异常
          RequestErrorBean err = RequestErrorBean.fromJsonMap(res);
          err.response = response;
          throw err;
        }

        // 仅返回成功的信息（针对数据为null时，dio库将返回{"code": 1, "data": null, "msg": null}的情况）
        if(res["data"] == null) {
          _temData = {"code": 1, "data": null, "msg": null};
        } else if(res["data"] is List &&  res["data"].length == 0){
          _temData = {"code": 1, "data": null, "msg": null};
        } else {
          _temData = res;
        }

        // 数据为null、[]等情况统一向下传递{"code": 1, "data": null, "msg": null}
        return _temData;
      }, onError: (e) async {
        // 满足该条件的为系统错误
        // 例如404，500等等
//        print(e.message);
//        print('----------------');
        if (e.message.indexOf('error') >= 0 ||
            e.message.indexOf('Error') >= 0 ||
            e.message.indexOf('Connecting timed out') >= 0) {
          // 强制转换成自定义的错误格式
          return RequestErrorBean.fromJsonMap(this.m);
        } else {
          // 后台定义的格式
          return e;
        }
      }));
    }
  }

  static HttpManager getInstance({String baseUrl}) {
    if (baseUrl == null) {
      return _instance._normal();
    } else {
      return _instance._baseUrl(baseUrl);
    }
  }

  //用于指定特定域名
  HttpManager _baseUrl(String baseUrl) {
    if (_dio != null) {
      _dio.options.baseUrl = baseUrl;
    }
    return this;
  }

  //一般请求，默认域名
  HttpManager _normal() {
    if (_dio != null) {
      if (_dio.options.baseUrl != BaseConfig.BASE_URL) {
        _dio.options.baseUrl = BaseConfig.BASE_URL;
      }
    }
    return this;
  }

  ///通用的GET请求
  /// * [api] 必填|请求路径（注：）
  /// * [params] 选填|请求的参数
  get(api, {params}) async {
    Response response;
    try {
      response = await _dio.get(api, queryParameters: params);
//      print(response.data);
      return response.data;
    } on RequestErrorBean catch (e) {
      //print("业务错误");
      //print(e.code);
      //RequestErrorBean err = RequestErrorBean.fromJsonMap(e);
      //return e;
      throw e;
    } on DioError catch (e) {
      //print("网络异常 post");
      //RequestErrorBean e = RequestErrorBean.fromJsonMap(this.m);
      throw e;
    }
  }

  ///通用的POST请求<br/>
  /// * [api] 必填|请求路径（注：）
  /// * [params] 选填|请求的参数
  post(api, {Map params}) async {
    Response response;
    try {
      response = await _dio.post(api, data: FormData.fromMap(params));
//      print(response.data);
      return response.data;
    } on RequestErrorBean catch (e) {
      throw e; // 报错错误交由viewmodel中处理
    } on DioError catch (e) {
      throw e; // 报错错误交由viewmodel中处理
    }
  }



}
